package br.com.toscano.contpedido.view.converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

@FacesConverter(value = "dateConverter")
public class DateConverter implements Converter {

  private static final String DD_MM_YY = "dd/MM/yy";
  private static final String DD_MM_YYYY = "dd/MM/yyyy";
  private SimpleDateFormat yyyyConvertor; 
  private SimpleDateFormat yyConvertor;

  public DateConverter() {
    yyyyConvertor = new SimpleDateFormat(DD_MM_YYYY);
    yyConvertor = new SimpleDateFormat(DD_MM_YY);
    yyConvertor.setLenient(false);
    yyyyConvertor.setLenient(false); 
  }
  
  public static String getDate(Date date) {
	  SimpleDateFormat yyyyConvertor = new SimpleDateFormat(DD_MM_YYYY);
	  yyyyConvertor.setLenient(false); 
	  return yyyyConvertor.format((Date)date);
  }
  
  public static Date getDate(String data) {
	  try {
		  SimpleDateFormat yyyyConvertor = new SimpleDateFormat(DD_MM_YYYY);
		  yyyyConvertor.setLenient(false); 

		  return (Date)yyyyConvertor.parseObject(data);
	  } catch (ParseException e) {
    	  return null;
      }
  }

  @Override
  public Object getAsObject(FacesContext fc, UIComponent component, String value) throws ConverterException {

   if( value==null || value.isEmpty()) {
      return new Date();
    }

    Date result = null;

    try {
      if (value.length() > DD_MM_YY.length()) { 
        result = (Date)yyyyConvertor.parseObject(value);
      } else {
        result = (Date)yyConvertor.parseObject(value); 
      }
    }
    catch (ParseException e) {
      FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR," Data Inválida.","Falha ao converter " + value + "");
  throw new ConverterException(message);
    }

    return result;
  }

  @Override
  public String getAsString(FacesContext fc, UIComponent component, Object date) throws ConverterException {
    try {
      return yyyyConvertor.format((Date)date);
    }
    catch (NullPointerException e) {
      return null;
    }
  }

}
